<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
class LoginController extends Controller
{
    /**
     * 展示登录页面
     *
     * @return 登录页面视图
     */
    public function login()
    {
        
        return view('Admin.login');
    }

    /**
     *  登录验证
     *
     * @return 
     */
    public function Loging(request $request)
    {
        
        //验证码验证
        if($request->input('Vcode') != session('Vcode')){
            return back()->with('error','验证码错误');
         }
        //查询数据库
        $data = DB::table('user')->where('username',$request->input('username'))->first();
        //判断用户是否存在
        if(!$data){
            return back()->with('error','用户名或密码错误');
        }
        //判断密码是否正确
        if(Hash::check($request->input('password'),$data->password)) {
            session(['uid'=>$data->id]);
            return redirect('/admin/index')->with('success','欢迎您'.$data->username);
            // dd(session('uid'));
        }else{
            return back()->with('error','用户名或密码错误');
        }
        
    }

    //生成验证码
    public function Vcode()
    {
        ob_clean();//清除输出缓存区的内容
        //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 120, $height = 35, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        session(['Vcode'=>$phrase]);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }

   
    /**
     * 执行退出登录
     *
     * @return 登录页面视图
     */
    public function logout(request $request)
    {
       $request->session()->forget('uid');

       return view('Admin.login');
    }

}
